package adminLoginPack;

import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import InvestmentPojo.EmailTempaltePojo;
import InvestmentPojo.MailSettings;
import InvestmentPojo.userInformationPojo;
import InvestmentPojo.userTablePojo;
import Notifications.notificationsDataLoading;

public class isUserExisAction extends Action {
 
 
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
 
       String method = "";
       String addUsrMethod = "";
       boolean admin = false;
       String adminValue = "";
       String username ="";
       String userId = "";
       String pwd = "";
       String userLastName = "";
       String surname = "";
       String dob ="";
       String email = "";
       String tel = "";
       String userAddress = "";
       String ptc = "";
       String userType = "";
       notificationsDataLoading dataLoading = null;
       CommonAdminPrevilegesAction cap = null;
       boolean isUserExist = false;
       MailSettings settings = null;
       try{
    	   
           method = (String)request.getParameter("method123");
           adminValue  = null != request.getParameter("admin")?(String)request.getParameter("admin"):"N";
           addUsrMethod= (String)request.getParameter("METHOD1234");
           if(null == method && "".equals(method))
           method = null != request.getParameter("a")?request.getParameter("a"):"";
           username  = null != (String)request.getParameter("username")?(String)request.getParameter("username"):"";
           userId = null != (String)request.getParameter("userIdforIns")?(String)request.getParameter("userIdforIns"):"";
           pwd = null != (String)request.getParameter("pwd")?(String)request.getParameter("pwd"):"";
           userLastName = null != (String)request.getParameter("userLastName")?(String)request.getParameter("userLastName"):"";
           Encryption enc = new Encryption();
           String encoding = enc.passwordEncryption(pwd);
           surname  = null != (String)request.getParameter("surname")?(String)request.getParameter("surname"):"";
           dob  = null != (String)request.getParameter("dob")?(String)request.getParameter("dob"):"";
           email = null != (String)request.getParameter("email")?(String)request.getParameter("email"):"";
           tel = null != (String)request.getParameter("tel")?(String)request.getParameter("tel"):"";
           userAddress = null != (String)request.getParameter("userAddress")?(String)request.getParameter("userAddress"):"";
           ptc = null != (String)request.getParameter("ptc")?(String)request.getParameter("ptc"):"";
           userType = null != (String)request.getParameter("registor")?(String)request.getParameter("registor"):"";
           dataLoading  = new notificationsDataLoading();
           cap = new CommonAdminPrevilegesAction();
           isUserExist = dataLoading.isUserExist(userId, "");
           settings = new MailSettings();
       if(null != addUsrMethod && addUsrMethod.equals("AddUser")){
           if(!isUserExist){
               userId = null != (String)request.getParameter("userIdforIns")?(String)request.getParameter("userIdforIns"):"";
               pwd = null != (String)request.getParameter("pwd")?(String)request.getParameter("pwd"):"";
               userAddress = null != (String)request.getParameter("userAddress")?(String)request.getParameter("userAddress"):"";
               if(!"".equals(adminValue) && adminValue.equals("Y") )
            	   admin = true;
               userTablePojo utp = new userTablePojo();
               utp.setUsername(username);
               utp.setUserId(userId);
               String password1 = generatePassword();
                   encoding = enc.passwordEncryption(password1);
                   SendEMail se = new SendEMail();
               utp.setPwd(encoding);
               utp.setSurname(userLastName);
               utp.setUsername(username);
               String dateofNotification1 = cap.DateFormatTest(dob);
               utp.setDatepicker(dob);
               utp.setEmail(email);
               String emailTemplateText = "";
               utp.setTel(tel);
               utp.setUserAddress(userAddress);
               utp.setPtc(ptc);
               utp.setAdmin(admin);
               utp.setUserType(userType);
               boolean flag = dataLoading.setUserInformation(utp);
               request.setAttribute("insertedFlag", flag);
               if(flag){
               		
               	 List li = dataLoading.getTemplateContent("email_templates", "templateid = 1 ", "templateName = \'User Registration\'" , "");
                 EmailTempaltePojo obj = null;
                 if(null != li && !li.isEmpty()){
              	   obj   = (EmailTempaltePojo) li.get(0);
                 }
                 emailTemplateText = obj.getTemplateText();
                 emailTemplateText = emailTemplateText.replaceAll("USERNAME", username);
                 emailTemplateText = emailTemplateText.replaceAll("USERID", userId);
                 emailTemplateText = emailTemplateText.replaceAll("PASSWORD", password1);
                 settings.setBody(emailTemplateText);
                 boolean sendmaiFlag = se.sendEmail(settings, email, "", obj.getSubject(),request);
                 if(sendmaiFlag){
                	 response.getWriter().write("Your registration is successful. Sign in with the account particulars for browsing and viewing the features of this site.");
                 }else{
                	 response.getWriter().write("<font color='red'>Some thing went wrong. Please try again or contact help desk (techsupport@investmentgateways.com).</font>");
                 }
               }else 
            	   response.getWriter().write("Please Try Again some Login Errors Occured.");
               }else{
            	   response.getWriter().write("Selected User already Exist. Please try with some other user Id");
               }
       }else if(null != addUsrMethod && addUsrMethod.equals("forgotPassword")){
    	   if(isUserExist){
           userId = null != (String)request.getParameter("userIdforIns")?(String)request.getParameter("userIdforIns"):"";
           String password1 = generatePassword();
           encoding = enc.passwordEncryption(password1);
           List userList = dataLoading.getUserData(userId, "investment_user1");
           userInformationPojo obj = (userInformationPojo)userList.get(0);
           username = obj.getUserFirstName()+", "+obj.getUserName(); 
           SendEMail se = new SendEMail(); 
           surname = null != (String)request.getParameter("surname")?(String)request.getParameter("surname"):"";
           if(!"".equals(adminValue) && adminValue.equals("Y") )
        	   admin = true;
           boolean flag = dataLoading.updatePassword("investment_user1", "user_password", encoding, "user_id='"+userId+"'", "","");
           if(flag){
        	   response.getWriter().write(userId+" Password is reset and sent to registered User mail id. Please login with your userid and new password to access.");
        	   List li = dataLoading.getTemplateContent("email_templates", "templateid = 2 ", "templateName = \'Reset Password\'" , "");
               EmailTempaltePojo obj1 = null;
               if(null != li && !li.isEmpty()){
            	   obj1   = (EmailTempaltePojo) li.get(0);
               }
               String emailTemplateText = obj1.getTemplateText();
               emailTemplateText = emailTemplateText.replaceAll("USERNAME", username);
               emailTemplateText = emailTemplateText.replaceAll("USERID", userId);
               emailTemplateText = emailTemplateText.replaceAll("PASSWORD", password1);
               settings.setBody(emailTemplateText);
               se.sendEmail(settings, obj.getUserEmailId(), "", obj1.getSubject(),request);
           }else{
        	   response.getWriter().write("Invalid Credentials Please tryagain "+userId+".");
           }
    	   }else{
    		   response.getWriter().write("User Does Not Exist Please Create Account.");
    	   }
       }else if(null != addUsrMethod && addUsrMethod.equals("UpdatePassword")){
    	   if(isUserExist){
           pwd = null != (String)request.getParameter("pwd")?(String)request.getParameter("pwd"):"";
           encoding = enc.passwordEncryption(pwd);
           String isUserAccess = null != (String)request.getParameter("isUserAccess")?(String)request.getParameter("isUserAccess"):"";
           String isAdminAccess = null != (String)request.getParameter("isAdminAccess")?(String)request.getParameter("isAdminAccess"):"";
           int i = 0;
           if(!"".equals(isAdminAccess) && isAdminAccess.equals("YES") )
        	   i = 1;
           boolean flag = dataLoading.updateUserPassword("investment_user1", "user_password", encoding, "user_id='"+userId+"'", "","");
           boolean flag1 = dataLoading.updateUserPassword("investment_user1", "isUserAccess", isUserAccess, "user_id='"+userId+"'", "","");
           boolean flag2 = dataLoading.updateUserPassword("investment_user1", "Admin_user_flag", String.valueOf(i) , "user_id='"+userId+"'", "","");
           
           if(flag && flag1 && flag2){
        	   response.getWriter().write(userId+" Password is Updated with "+pwd+" Please login with your userid, and new password to access.");
           }else{
        	   response.getWriter().write("Invalid Credentials Please tryagain "+userId+".");
           }
    	   }
    	   }else if(null != addUsrMethod && addUsrMethod.trim().equals("changePassword")){
	   
	   if(isUserExist){
       pwd = null != (String)request.getParameter("pwd")?(String)request.getParameter("pwd"):"";
       encoding = enc.passwordEncryption(pwd);
       String isUserAccess = null != (String)request.getParameter("isUserAccess")?(String)request.getParameter("isUserAccess"):"YES";
       String isAdminAccess = null != (String)request.getParameter("isAdminAccess")?(String)request.getParameter("isAdminAccess"):"";
       int i = 0;
       if(!"".equals(isAdminAccess) && isAdminAccess.equals("YES") )
    	   i = 1;
       boolean flag = dataLoading.updateUserPassword("investment_user1", "user_password", encoding, "user_id='"+userId+"'", "","");
       boolean flag1 = dataLoading.updateUserPassword("investment_user1", "isUserAccess", isUserAccess, "user_id='"+userId+"'", "","");
       boolean flag2 = dataLoading.updateUserPassword("investment_user1", "Admin_user_flag", String.valueOf(i) , "user_id='"+userId+"'", "","");
       if(flag && flag1 && flag2){
    	   List userList = dataLoading.getUserData(userId, "investment_user1");
           userInformationPojo obj = (userInformationPojo)userList.get(0);
           username = obj.getUserFirstName()+", "+null != obj.getUserMiddleName()?obj.getUserMiddleName():""; 
           SendEMail se = new SendEMail();
        	   response.getWriter().write(userId+" Password is updated with given password and sent to registered User mail id. Please login with your userid and new password to access.");
        	   List li = dataLoading.getTemplateContent("email_templates", "templateid = 3 ", "templateName = \'Change Password\'" , "");
               EmailTempaltePojo obj1 = null;
               if(null != li && !li.isEmpty()){
            	   obj1   = (EmailTempaltePojo) li.get(0);
               }
               String emailTemplateText = obj1.getTemplateText();
               emailTemplateText = emailTemplateText.replaceAll("USERNAME", username);
               emailTemplateText = emailTemplateText.replaceAll("USERID", userId);
               emailTemplateText = emailTemplateText.replaceAll("PASSWORD", pwd);
               settings.setBody(emailTemplateText);
               se.sendEmail(settings, obj.getUserEmailId(), "",obj1.getSubject() ,request);
       }else{
        	   response.getWriter().write("Invalid Credentials Please tryagain "+userId+".");
           }
       }else{
    	   response.getWriter().write("Invalid Credentials Please tryagain "+userId+".");
       }
	   }else{
		   response.getWriter().write("User Does Not Exist Please Create Account.");
	   }
       }catch(Exception e){
    	   e.printStackTrace();
       }
       return mapping.findForward("");
    }
public String generatePassword(){
    	String regis = "";
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random rng = new Random();
            char[] text = new char[8];
            for (int i = 0; i < 8; i++)
            {
                text[i] = characters.charAt(rng.nextInt(characters.length()));
            }
            System.out.println(new String(text));  
            regis = new String(text);
    	return regis;
    }
}
